package com.asman.worker.widgets.multiFile

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Handler
import android.util.AttributeSet
import android.view.View
import android.widget.FrameLayout
import android.widget.TextView
import androidx.core.view.children
import androidx.core.view.doOnPreDraw
import androidx.fragment.app.FragmentActivity
import androidx.gridlayout.widget.GridLayout
import com.asman.worker.R
import com.asman.worker.multishow.ImageTitle
import com.asman.worker.multishow.MultiShowActivity
import com.asman.worker.rn.NativeTakePhoto
import com.asman.worker.utils.SizeUtils.dp2px
import com.facebook.react.bridge.BaseActivityEventListener
import com.facebook.react.bridge.ReactContext
import com.jph.takephoto.model.TResult
import com.utils.PhotoBottomSheet
import com.utils.TakePhotoCallBack
import showToast
import com.facebook.react.views.textinput.ContentSizeWatcher
import log


class AddImageGridLayout @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {

    var maxCount: Int = 1
        set(value) {
            field = value
            gridLayout.rowCount = maxCount / 3 + 1
        }

    var videoEnable: Boolean = false

    var gridLayout: GridLayout

    var tvGridAddEmpty: TextView

    var itemWidth = dp2px(100f)

    var datas: MutableList<ImageUploadData> = arrayListOf(ImageUploadData(status = 0))

    var imageCount = 0

    lateinit var photoBottomSheet: PhotoBottomSheet

    private val mActivityEventListener = object : BaseActivityEventListener() {
        override fun onActivityResult(
            activity: Activity?, requestCode: Int, resultCode: Int, data: Intent?
        ) {
            photoBottomSheet.onActivityResult(requestCode, resultCode, data)
        }
    }

    init {
        View.inflate(context, R.layout.layout_grid_add_image, this)
        gridLayout = findViewById(R.id.gridLayout)
        tvGridAddEmpty = findViewById(R.id.tv_grid_add_empty)
        tvGridAddEmpty.visibility = View.GONE
        gridLayout.columnCount = 3
        this.doOnPreDraw {
            itemWidth = width / 3
            addAddView()
        }
    }

    var reactContext: ReactContext? = null
        set(value) {
            field = value
            value?.addActivityEventListener(mActivityEventListener)
        }

    fun getModule(reactContext: ReactContext): NativeTakePhoto {
        return reactContext.getNativeModule(NativeTakePhoto::class.java)
    }

    interface OnFirstAddClickListener {
        fun onClick()
    }

    var listener: OnFirstAddClickListener? = null

    fun setOnFirstAddClickListener(listener: OnFirstAddClickListener?) {
        this.listener = listener
    }

    var viewAdd: MultiImageUploadLayout? = null

    private fun addAddView() {
        viewAdd = MultiImageUploadLayout(context)
        viewAdd?.layoutParams = LayoutParams(itemWidth, itemWidth)
        viewAdd?.initType(ImageUploadData(status = 0))
        viewAdd?.setOnCallBackListener(object : MultiImageUploadLayout.OnCallBack() {
            override fun onAddClickListener() {
                if (listener != null && imageCount == 1) {
                    listener?.onClick()
                } else {
                    //点击添加图片
                    showPhotoDialog()
                }
            }
        })
        gridLayout.addView(viewAdd)
        imageCount++
        requestLayout()
        checkCount()
    }

    //显示选择对话框
    fun showPhotoDialog() {
        //剩余可选张数
        val lastCount = maxCount - datas.size + (if (datas[datas.size - 1].status == 0) 1 else 0)
        photoBottomSheet = PhotoBottomSheet.get()
        if (reactContext != null) {
            getModule(reactContext!!).photoBottomSheet = photoBottomSheet
        }
        photoBottomSheet.show(
            (context as FragmentActivity).supportFragmentManager, lastCount,
            videoEnable,
            object : TakePhotoCallBack.OnChoosePhoneResult {
                override fun onHandlerSuccess(result: TResult) {
                    if (result.image != null) {
                        //填充数据
                        result.images.map {
                            val insertIndex = datas.size - 1
                            val data = ImageUploadData(1, localPath = it.originalPath)
                            datas.add(insertIndex, data)
                            addImageView(data)
                        }
                    } else {
                        showToast("获取图片失败")
                    }
                }

                override fun onHandlerFailure(errorMsg: String) {
                }
            })
    }

    //回写上一次上传完的图片
    fun setLastImages(imageUrls: List<String?>?) {
        this.doOnPreDraw {
            itemWidth = width / 3
            //回写的时候先清除当前所有的数据
            gridLayout.removeAllViews()
            datas = arrayListOf(ImageUploadData(status = 0))
            imageCount = 0
            addAddView()
            checkCount()

            //这里不做一个延时处理，高度不会自动增加
            Handler().postDelayed({
                //填充数据
                imageUrls?.map {
                    val data = ImageUploadData(3, url = it)
                    datas.add(data)
                    addImageView(data)
                }
            }, 200)
        }
    }

    //显示本地图片，并且开始上传
    private fun addImageView(data: ImageUploadData) {
        tvGridAddEmpty.visibility = View.GONE
        val view = MultiImageUploadLayout(context)
        view.initOSS(bucketName, endpoint)
        view.layoutParams = LayoutParams(itemWidth, itemWidth)
        view.initType(data)
        view.setOnCallBackListener(object : MultiImageUploadLayout.OnCallBack() {
            override fun onAddClickListener() {
            }

            override fun onDeleteClickListener(data: ImageUploadData) {
                datas.remove(data)
                gridLayout.removeView(view)
                imageCount--
                requestLayout()
                checkCount()
            }

            override fun onImageListener(data: ImageUploadData) {
                //点击查看
                val images = datas.filter {
                    it.status != 0
                }.map {
                    ImageTitle(it.localPath ?: (it.url ?: ""), "")
                }
                if (context is Activity) {
                    MultiShowActivity.start(context as Activity, images, datas.indexOf(data))
                }
            }
        })
        gridLayout.addView(view, gridLayout.childCount - 1)
        imageCount++
        requestLayout()
        checkCount()
    }

    //检查文件个数
    fun checkCount() {
        if (imageCount > maxCount) {
            viewAdd?.visibility = View.GONE
        } else {
            viewAdd?.visibility = View.VISIBLE
        }
        doOnPreDraw {
            callBack?.onChanged(width, if (height == 0) itemWidth else height)
        }
    }

    var callBack: OnSizeChangeCallBack? = null

    interface OnSizeChangeCallBack {
        fun onChanged(width: Int, height: Int)
    }

    fun setOnSizeChange(callBack: OnSizeChangeCallBack) {
        this.callBack = callBack
    }

    fun showEmptyTips(text: String) {
        tvGridAddEmpty.visibility = View.VISIBLE
        tvGridAddEmpty.text = text
        tvGridAddEmpty.layoutParams.width = itemWidth - dp2px(16f)
    }

    //停止上传
    fun onDestroy() {
        val ite = gridLayout.children.iterator()
        while (ite.hasNext()) {
            val view = ite.next()
            if (view is MultiImageUploadLayout) {
                view.onDestroy()
            }
        }
    }

    var bucketName: String? = null
    var endpoint: String? = null

    fun initOSS(bucketName: String?, endpoint: String?) {
        this.bucketName = bucketName
        this.endpoint = endpoint
    }

    fun getOSSImageUrls(): List<String>? {
        return if (isAllImageOk()) {
            val images = arrayListOf<String>()
            for (aa in datas) {
                if (aa.url != null) {
                    images.add(aa.url!!.substringBefore("?"))
                }
            }
            images
        } else null
    }

    //是否所有的都上传完了
    fun isAllImageOk(): Boolean {
        return datas.find { it.status != 3 && it.localPath != null } == null
    }

    private var mContentSizeWatcher: ContentSizeWatcher? = null

    fun setContentSizeWatcher(contentSizeWatcher: ContentSizeWatcher) {
        mContentSizeWatcher = contentSizeWatcher
    }

    //Android 动态addView RN 页面不刷新问题
    override fun requestLayout() {
        super.requestLayout()
        post(measureAndLayout)
    }

    private val measureAndLayout = Runnable {
        measure(
            MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY),
            MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY)
        )
        layout(left, top, right, bottom)
    }
}